package com.harmontronics.hanma.paas.paas.common;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: PageRequest
 * @Description: 分页请求基类
 * @Author: tylr
 * @Date: 2019/7/17 14:04
 * @Version: 1.0.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBase<T> {

    /**
     * 每页记录数，默认10
     */
    @ApiModelProperty(value = "每页记录数",required = true)
    private int pageSize = 10;
    /**
     * 当前页 默认1
     */
    @ApiModelProperty(value = "当前页码",required = true)
    private int pageNo = 1;
    /**
     * 总记录数
     */
    @ApiModelProperty(value = "总记录数",required = true)
    private long totalCount;
    /**
     * 总页数
     */
    @ApiModelProperty(value = "总页数",required = true)
    private long totalPage;
    /**
     * 数据
     */
    @ApiModelProperty(value = "数据",required = true)
    private List<T> data;

    public PageBase(IPage<T> pageInfo) {
        this.totalCount = pageInfo.getTotal();
        this.totalPage = pageInfo.getPages();
        this.data = pageInfo.getRecords();
        this.pageNo = (int) pageInfo.getCurrent();
        this.pageSize = (int) pageInfo.getSize();
    }


    public static <T> PageBase<T> from(IPage pageInfo,Class<T> clazz) {
        PageBase<T> pageBase=new PageBase<>();
        pageBase.totalCount = pageInfo.getTotal();
        pageBase.totalPage = pageInfo.getPages();
        pageBase.data = Convert.toList(clazz,pageInfo.getRecords());
        pageBase.pageNo = (int) pageInfo.getCurrent();
        pageBase.pageSize = (int) pageInfo.getSize();
        return pageBase;

    }

    public PageBase<T> copy(PageBase pageBase) {
        this.totalCount = pageBase.totalCount;
        this.totalPage = pageBase.totalPage;
        this.pageNo = pageBase.pageNo;
        this.pageSize = pageBase.pageSize;
        this.data = new ArrayList<>();
        return this;
    }

    public static <T>PageBase<T> copy(PageBase pageBase,Class<T> targetClass) {
        PageBase<T> resultPage=new PageBase<>();
        resultPage.totalCount = pageBase.totalCount;
        resultPage.totalPage = pageBase.totalPage;
        resultPage.pageNo = pageBase.pageNo;
        resultPage.pageSize = pageBase.pageSize;
        resultPage.setData(Convert.toList(targetClass,pageBase.getData()));
        return resultPage;
    }

    public PageBase<T> empty(int pageNo,int pageSize){
        this.totalPage = 0;
        this.totalCount = 0;
        this.setData(new ArrayList<>());
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        return this;
    }


    public boolean isEmpty(){
        return data == null || data.isEmpty();
    }
}
